package cn.itcast.controller.cargo;


import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ContractProductVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController{


    @Reference
    private ContractService contractService;

    @Autowired
    private DownloadUtil downloadUtil;


    @RequestMapping(value = "/list",name = "分页展示所有购销合同列表")
    public String list(String companyId,@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "10")int pageSize){

        //构建查询条件   通过公司id 查询所有合同
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria().andCompanyIdEqualTo(getCompanyId());

        User user = getUser();
        Integer degree = user.getDegree();//获取登录人的级别
        //        1-企业管理员
        //        2-管理所有下属部门和人员
        //        3-管理本部门
        //        4-普通员工
        if(degree == 4 ){
            //普通员工   给查询条件做个限制 根据添加合同的人id的  id 去查询
            criteria.andCreateByEqualTo(user.getId());

        }else if(degree == 3){
            //部门经理     //部门id
            criteria.andCreateDeptEqualTo(user.getDeptId());
        }else if(degree == 2){
            // 管理所有下属部门和人员
            criteria.andCreateDeptLike(user.getDeptId()+"%");
        }



        /*通过合同的常见时间排序*/
        example.setOrderByClause("create_time desc");

        PageInfo<Contract> pageInfo =  contractService.findAll(example,page,pageSize);

        request.setAttribute("page",pageInfo);

        return "/cargo/contract/contract-list";
    }



    @RequestMapping(value = "/toAdd",name = "跳转到新增合同页面")
    public String toAdd(){

        return "/cargo/contract/contract-add";
    }


    @RequestMapping(value = "/edit",name = "跳转到新增合同方法")
    public String edit(Contract contract){

        /*合同id 为空即新增 不为空即 保存*/
        if (StringUtils.isEmpty(contract.getId())) {
            //设置id 公司id  公司名
            contract.setId(UUID.randomUUID().toString());
            contract.setCompanyName(getCompanyName());
            contract.setCompanyId(getCompanyId());
            /*设置创建时间*/
            contract.setCreateTime(new Date());
            contract.setState(0);//设置状态  0：草稿 ，1:已确认

            contract.setCreateBy(getUser().getId());//添加一个创建合同的人的id

            contract.setCreateDept(getUser().getDeptId());//添加一个创建合同的人的部门id

            contractService.save(contract);
        }else{
            contractService.update(contract);
        }


        return "redirect:/cargo/contract/list.do";
    }


    @RequestMapping(value = "/toUpdate",name = "跳转到编辑合同页面")
    public String toUpdate(String id){//合同id
        /*数据回显 根据合同id  查找对应合同*/
        Contract contract = contractService.findById(id);

        request.setAttribute("contract",contract);
        return "/cargo/contract/contract-update";
    }



    @RequestMapping(value = "/submit",name = "提交购销合同")
    public String submit(String id){//合同id
        //更新合同上state对应的状态码
        Contract contract = contractService.findById(id);
        contract.setState(1);
        contractService.update(contract);

        return "redirect:/cargo/contract/list.do";
    }


    @RequestMapping(value = "/cancel",name = "取消购销合同")
    public String cancel(String id){//合同id
        //更新合同上state对应的状态码
        Contract contract = contractService.findById(id);
        contract.setState(0);
        contractService.update(contract);

        return "redirect:/cargo/contract/list.do";
    }


    @RequestMapping(value = "/delete",name = "删除购销合同")
    public String delete(String id){//合同id

        contractService.delete(id);

        return "redirect:/cargo/contract/list.do";
    }


    @RequestMapping(value = "/print",name = "跳转到下载出货表页面")
    public String print(){//合同id

        return "/cargo/print/contract-print";
    }


    @RequestMapping(value = "/printExcel",name = "下载出货表方法")
    public void printExcel(String inputDate ) throws Exception {//合同id

        //根据船期查询数据
        List<ContractProductVo> ContractProductVo = contractService.findContractProductVoByShipTime(inputDate,getCompanyId());
//      获取模板
        String realPath = session.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
//       创建工作簿（里边是模板）
        Workbook workbook = new  XSSFWorkbook(new FileInputStream(realPath));

        //获取工作表
        Sheet sheet = workbook.getSheetAt(0);

        sheet.getRow(0).getCell(1).setCellValue(inputDate.replace("-0","年").replace("-","年")  +"月份出货表");

        //获取样式
        CellStyle[] cellStyles = new CellStyle[8];
        int rowIndex  =2;
        Row row = null;
        Cell cell = null;
        row = sheet.getRow(2);

        for (int i = 1; i <=8; i++) {
            cellStyles[i-1] = row.getCell(i).getCellStyle();
        }
        for (cn.itcast.vo.ContractProductVo contractProductVo : ContractProductVo) {

            row =   sheet.createRow(rowIndex);
            row.setHeightInPoints(26);
//            客户	合同号	货号	数量	工厂	工厂交期	船期	贸易条款
            cell = row.createCell(1);
            cell.setCellValue(contractProductVo.getCustomName());
            cell.setCellStyle(cellStyles[0]);

            cell = row.createCell(2);
            cell.setCellValue(contractProductVo.getContractNo());
            cell.setCellStyle(cellStyles[1]);

            cell = row.createCell(3);
            cell.setCellValue(contractProductVo.getProductNo());
            cell.setCellStyle(cellStyles[2]);

            cell = row.createCell(4);
            cell.setCellValue(contractProductVo.getCnumber());
            cell.setCellStyle(cellStyles[3]);

            cell = row.createCell(5);
            cell.setCellValue(contractProductVo.getFactoryName());
            cell.setCellStyle(cellStyles[4]);
//            工厂交期	船期	贸易条款

            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getDeliveryPeriod()));
            cell.setCellStyle(cellStyles[5]);

            cell = row.createCell(7);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(contractProductVo.getShipTime()));
            cell.setCellStyle(cellStyles[6]);

            cell = row.createCell(8);
            cell.setCellValue(contractProductVo.getTradeTerms());
            cell.setCellStyle(cellStyles[7]);
            rowIndex++;
        }

//        文件导出 文件下载 一个流：文件的输出流  两个头：文件的打开方式、文件的mime类型
//        ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream); //把workbook中的内容写入到缓存流中
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");
    }
}
